/**
 * Notes: 云函数非标业务处理
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux@qq.com
 * Date: 2021-10-21 04:00:00 
 */
function handlerOther(event) {
	console.log('🔍 handlerOther 开始处理事件');
	// console.log('原始事件类型:', typeof event);
	// console.log('原始事件键值:', event ? Object.keys(event) : []);
	// console.log('完整事件内容:', JSON.stringify(event, null, 2));
	
	let isOther = false;

	// console.log('=== handlerOther 开始处理 ===');
	// console.log('事件类型检查:', {
	// 	hasFromUserName: !!event?.FromUserName,
	// 	hasMsgType: !!event?.MsgType,
	// 	hasOutTradeNo: !!(event?.outTradeNo || event?.out_trade_no),
	// 	hasResultCode: !!event?.resultCode,
	// 	hasHttpMethod: !!event?.httpMethod,
	// 	httpMethod: event?.httpMethod,
	// 	hasWechatSignature: !!(event?.headers && event?.headers['wechatpay-signature']),
	// 	hasPath: !!(event?.path || event?.url)
	// });

	if (!event) {
		console.log('事件对象为空，返回原始事件');
		return {
			isOther,
			eventX: event
		};
	}

	// 新增：若已提供标准 route，优先尊重并跳过非标处理，避免被误识别为支付/退款回调
	if (event.route) {
		console.log('🔎 检测到标准路由，跳过非标处理:', event.route);
		return {
			isOther: false,
			eventX: event
		};
	}

	// 公众号事件处理
	if (event['FromUserName'] && event['MsgType']) {
		console.log('公众号事件处理');
		let ret = {
			route: 'oa/serve',
			params: event
		}
		return {
			isOther: true,
			eventX: ret
		};
	}

	// CloudPay 支付回调（云函数直接回调事件）
	if (event.outTradeNo || event.out_trade_no || event.resultCode || event.returnCode) {
		console.log('CloudPay 支付通知处理');
		return {
			isOther: true,
			eventX: {
				route: 'payment/callback',
				params: event
			}
		};
	}

	// 新增：CloudPay 退款回调识别
	if (event.outRefundNo || event.out_refund_no || event.refundId) {
		console.log('CloudPay 退款通知处理');
		return {
			isOther: true,
			eventX: {
				route: 'payment/callback',
				params: Object.assign({}, event, { refund: true })
			}
		};
	}

	// HTTP 触发器处理（例如：微信支付 v3 回调）
	if (event.httpMethod) {
		console.log('🌐 HTTP触发器处理开始');
		const path = (event.path || event.url || '').toLowerCase();
		const headers = event.headers || {};
		// 保留原始 body 串用于签名验签
		const bodyRaw = typeof event.body === 'string' ? event.body : JSON.stringify(event.body || {});
		
		console.log('HTTP请求详情:', {
			method: event.httpMethod,
			path: path || '无path字段',
			originalPath: event.path,
			originalUrl: event.url,
			hasWechatSignature: !!headers['wechatpay-signature'],
			contentType: headers['content-type']
		});

		// 如果是根路径或没有path信息，但是有微信支付回调的特征头部，则根据请求体内容推断回调类型
		if ((!path || path === '/') && headers['wechatpay-signature']) {
			// console.log('✅ 检测到微信支付回调，但缺少path信息，尝试从请求体推断回调类型');
			// console.log('微信支付回调详情:', {
			// 	httpMethod: event.httpMethod,
			// 	contentType: headers['content-type'],
			// 	wechatSignature: headers['wechatpay-signature'] ? '存在' : '不存在',
			// 	wechatTimestamp: headers['wechatpay-timestamp'],
			// 	wechatNonce: headers['wechatpay-nonce'],
			// 	bodyLength: bodyRaw ? bodyRaw.length : 0
			// });
			
			try {
				const bodyObj = typeof event.body === 'string' ? JSON.parse(event.body) : event.body;
				let targetRoute = 'payment/callback'; // 默认为通用回调，由控制器解密后分发
				
				// 尝试从请求体中提取out_trade_no来判断回调类型
				if (bodyObj && bodyObj.resource && bodyObj.resource.ciphertext) {
					// 这是加密的微信支付回调，无法直接解析out_trade_no
					// 根据event_type无法可靠判断订单类型，这里保持通用回调，交由控制器解密后判定
					if (bodyObj.event_type) {
						console.log('检测到事件类型:', bodyObj.event_type);
					}
				} else if (bodyObj && bodyObj.out_trade_no) {
					// 未加密的回调数据，可以直接根据out_trade_no判断
					const outTradeNo = bodyObj.out_trade_no;
					console.log('检测到订单号:', outTradeNo);
					
					if (outTradeNo.startsWith('RCH')) {
						targetRoute = 'payment/recharge_callback';
						console.log('🔄 根据订单号前缀RCH识别为充值回调');
					} else if (outTradeNo.startsWith('DEV')) {
						targetRoute = 'payment/device_callback';
						console.log('🔄 根据订单号前缀DEV识别为设备回调');
					} else if (outTradeNo.startsWith('APT') || outTradeNo.includes('APPOINTMENT')) {
						targetRoute = 'payment/callback';
						console.log('🔄 根据订单号前缀APT识别为预约回调');
					} else {
						console.log('🔄 未识别的订单号格式，默认为通用回调 payment/callback');
					}
				} else {
					console.log('🔄 无法从请求体提取订单信息，默认为通用回调 payment/callback');
				}
				
				console.log('🔄 微信支付回调路由到:', targetRoute);
				const result = {
					isOther: true,
					eventX: {
						route: targetRoute,
						params: { headers, bodyRaw }
					}
				};
				// console.log('✅ 微信支付回调路由成功，返回结果:', JSON.stringify(result, null, 2));
				return result;
			} catch (e) {
				console.error('解析微信支付回调请求体失败:', e);
				// 如果解析失败，路由到通用回调处理
				const result = {
					isOther: true,
					eventX: {
						route: 'payment/callback',
						params: { headers, bodyRaw }
					}
				};
				console.log('✅ 微信支付回调路由成功（解析失败后的备用处理），返回结果:', JSON.stringify(result, null, 2));
				return result;
			}
		}

		// 预约支付回调
		if (path.includes('/wxpay/notify/appointment') || path.endsWith('/payment/callback')) {
			return {
				isOther: true,
				eventX: {
					route: 'payment/callback',
					params: { headers, bodyRaw }
				}
			};
		}

		// 充值支付回调
		if (path.includes('/wxpay/notify/recharge') || path.endsWith('/payment/recharge_callback')) {
			return {
				isOther: true,
				eventX: {
					route: 'payment/recharge_callback',
					params: { headers, bodyRaw }
				}
			};
		}

		// 设备订单支付回调
		if (path.includes('/wxpay/notify/device') || path.endsWith('/payment/device_callback')) {
			return {
				isOther: true,
				eventX: {
					route: 'payment/device_callback',
					params: { headers, bodyRaw }
				}
			};
		}

		// 新增：退款通知回调（微信支付 v3）
		if (path.includes('/wxpay/notify/refund') || path.endsWith('/payment/refund_callback')) {
			return {
				isOther: true,
				eventX: {
					route: 'payment/callback',
					params: { headers, bodyRaw, refund: true }
				}
			};
		}

		// 新增：HTTP 触发器直调 - 微信支付订单查询（商户订单号）
		if (path.includes('/api/payment/query_by_out_trade_no') || path.endsWith('/payment/query_by_out_trade_no')) {
			const qs = event.queryStringParameters || event.queryParameters || {};
			const outTradeNo = qs.out_trade_no || qs.outTradeNo || '';
			console.log('HTTP直调-查询订单(商户单号):', { outTradeNo });
			return {
				isOther: true,
				eventX: {
					route: 'payment/query_by_out_trade_no',
					params: { out_trade_no: outTradeNo }
				}
			};
		}

		// 新增：HTTP 触发器直调 - 微信支付订单查询（微信订单号）
		if (path.includes('/api/payment/query_by_transaction_id') || path.endsWith('/payment/query_by_transaction_id')) {
			const qs = event.queryStringParameters || event.queryParameters || {};
			const transactionId = qs.transaction_id || qs.transactionId || '';
			console.log('HTTP直调-查询订单(微信单号):', { transactionId });
			return {
				isOther: true,
				eventX: {
					route: 'payment/query_by_transaction_id',
					params: { transaction_id: transactionId }
				}
			};
		}

		// 新增：HTTP 触发器直调 - 微信支付退款申请
		if (path.includes('/api/payment/refund') || path.endsWith('/payment/refund')) {
			let bodyObj = {};
			try {
				bodyObj = typeof event.body === 'string' ? JSON.parse(event.body || '{}') : (event.body || {});
			} catch (e) {
				console.error('解析退款请求体失败:', e.message);
				bodyObj = {};
			}
			const params = {
				out_trade_no: bodyObj.out_trade_no || bodyObj.outTradeNo || '',
				out_refund_no: bodyObj.out_refund_no || bodyObj.outRefundNo || '',
				total: bodyObj.total || 0,
				refund: bodyObj.refund || 0,
				reason: bodyObj.reason || ''
			};
			console.log('HTTP直调-申请退款:', params);
			return {
				isOther: true,
				eventX: {
					route: 'payment/refund',
					params
				}
			};
		}
	}

	// console.log('❌ 未匹配到任何处理逻辑，返回原始事件');
	// console.log('最终事件状态:', {
	// 	isOther: false,
	// 	eventType: typeof event,
	// 	eventKeys: event ? Object.keys(event) : []
	// });
	
	return {
		isOther,
		eventX: event
	};
}

module.exports = {
	handlerOther,
}